'''
    括号匹配：开始符号入栈，遇到结束符号就出栈，若出栈和结束符号相同就可以。最终结束条件：栈为空且匹配
    两种写法：第一种我写的，另一种教材上，其实一样
'''
from Stack import Stack

def parChecker1(symolString):
    s = Stack()
    balanced = True # 是否匹配，默认匹配
    index = 0   # 读取字符的下标
    while index < len(symolString) and balanced:
        symbol = symolString[index]
        # 下面语句自己写的稍微有点复杂，可以有一种简洁写法：if symbol in "([{":
        if symbol == '(' or symbol == '[' or symbol == '{' or symbol == '<':    # 开始符号
            s.push(symbol)
        else:   # 结束符号
            if s.isEmpty(): # 空了还有结束符号
                balanced = False
            else:
                pop = s.pop()
                if (pop == '<' and symbol == '>') or (pop == '{' and symbol == '}') or (pop == '[' and symbol == ']') or (pop == '(' and symbol == ')'):
                    balanced = True
                else:
                    balanced = False
        index = index + 1
        s.printstack()
    if balanced and s.isEmpty():
        return True
    else:
        return False

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top,symbol):
                       balanced = False
        index = index + 1
    if balanced and s.isEmpty():
        return True
    else:
        return False

def matches(open,close):
    opens = "([{"
    closers = ")]}"
    return opens.index(open) == closers.index(close)

if __name__ == '__main__':
    print(parChecker1('(([[[{{}}]]]))'))
    print(parChecker1('()'))
    print(parChecker1('{{([][])}()}'))
    print(parChecker1('[{()]'))